package com.niuwa.p2p.service.impl.credit;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.niuwa.p2p.core.utils.FileUtil;
import com.niuwa.p2p.entity.credit.ArtificialNationalInfo;
import com.niuwa.p2p.entity.credit.CompanyCheckReqInfo;
import com.niuwa.p2p.entity.credit.CompanyCourtInfo;
import com.niuwa.p2p.entity.credit.CorpBaseNationalInfo;
import com.niuwa.p2p.entity.credit.CreditInvestigationInfo;
import com.niuwa.p2p.entity.credit.NationalPersonShareholderReport;
import com.niuwa.p2p.entity.credit.PersonBaseInfo;
import com.niuwa.p2p.entity.credit.PersonCheckInfo;
import com.niuwa.p2p.entity.credit.PersonCheckReqInfo;
import com.niuwa.p2p.entity.credit.PersonCourtInfo;
import com.niuwa.p2p.entity.credit.PersonTopManagerInfo;
import com.niuwa.p2p.entity.credit.QueryConditionInfo;
import com.niuwa.p2p.service.credit.PyXmlService;

/*
 * 
 * @title  鹏元接口xml实现
 *
 * @author tennyqin, cupid
 * @version 1.0
 * @created 2015年4月2日
 */
@Service
public class PyXmlServiceImpl implements PyXmlService {
    
    private static Logger logger = Logger.getLogger(PyXmlServiceImpl.class);

    @Override
    public String createPersonXml(PersonCheckReqInfo req) {
        String xmlStr = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            document.setXmlVersion("1.0");
            Element root = document.createElement("conditions");
            document.appendChild(root);

            Element condition = document.createElement("condition");
            condition.setAttribute("queryType", String.valueOf(req.getQueryType()));

            Element item = document.createElement("item");
            Element name = document.createElement("name");
            name.setTextContent("name");
            item.appendChild(name);
            Element value = document.createElement("value");
            value.setTextContent(req.getName());
            item.appendChild(value);

            Element item2 = document.createElement("item");
            Element name2 = document.createElement("name");
            name2.setTextContent("documentNo");
            item2.appendChild(name2);
            Element value2 = document.createElement("value");
            value2.setTextContent(req.getDocumentNo());
            item2.appendChild(value2);

            Element item3 = document.createElement("item");
            Element name3 = document.createElement("name");
            name3.setTextContent("subreportIDs");
            item3.appendChild(name3);
            Element value3 = document.createElement("value");
            value3.setTextContent(req.getSubreportIDs());
            item3.appendChild(value3);

            Element item4 = document.createElement("item");
            Element name4 = document.createElement("name");
            name4.setTextContent("refID");
            item4.appendChild(name4);
            Element value4 = document.createElement("value");
            value4.setTextContent(req.getRefID());
            item4.appendChild(value4);

            condition.appendChild(item);
            condition.appendChild(item2);
            condition.appendChild(item3);
            condition.appendChild(item4);
            root.appendChild(condition);

            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transFormer = transFactory.newTransformer();
            transFormer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            transFormer.transform(domSource, new StreamResult(bos));
            xmlStr = bos.toString();
        } catch (ParserConfigurationException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        } catch (TransformerException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        }
        return replaceCharset(xmlStr);
    }

    @Override
    public CreditInvestigationInfo parserPersonXml(String rsp, String documentNo) {
        CreditInvestigationInfo creditInvestigationInfo = new CreditInvestigationInfo();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader sr = new StringReader(rsp);
            InputSource is = new InputSource(sr);
            Document doc = builder.parse(is);
            // 根节点
            Element rootElement = doc.getDocumentElement();
            NamedNodeMap cisReports = rootElement.getAttributes();
            String batNo = cisReports.getNamedItem("batNo").getNodeValue();
            creditInvestigationInfo.setBatNo(batNo);
            String unitName = cisReports.getNamedItem("unitName").getNodeValue();
            creditInvestigationInfo.setUnitName(unitName);
            String subOrgan = cisReports.getNamedItem("subOrgan").getNodeValue();
            creditInvestigationInfo.setSubOrgan(subOrgan);
            String queryUserID = cisReports.getNamedItem("queryUserID").getNodeValue();
            creditInvestigationInfo.setQueryUserID(queryUserID);
            String queryCount = cisReports.getNamedItem("queryCount").getNodeValue();
            creditInvestigationInfo.setQueryCount(queryCount);
            String receiveTime = cisReports.getNamedItem("receiveTime").getNodeValue();
            creditInvestigationInfo.setReceiveTime(receiveTime);
            NodeList nList = doc.getElementsByTagName("cisReport");

            Date currentDate = new Date();
            // 对于SingleQuery,将对用户的证件号码进行存储和标识;
            // 认证头部信息
            if (null != nList && nList.getLength() > 0) {
                // 遍历该集合，显示结合中的元素及其子元素的名字
                for (int cis = 0; cis < nList.getLength(); cis++) {
                    Element cisReport = (Element) nList.item(cis);
                    String reportID = cisReport.getAttributes().getNamedItem("reportID").getNodeValue();
                    creditInvestigationInfo.setReportID(reportID);
                    String buildEndTime = cisReport.getAttributes().getNamedItem("buildEndTime").getNodeValue();
                    creditInvestigationInfo.setBuildEndTime(buildEndTime);
                    String queryReasonID = cisReport.getAttributes().getNamedItem("queryReasonID").getNodeValue();
                    creditInvestigationInfo.setQueryReasonID(queryReasonID);
                    String subReportTypes = cisReport.getAttributes().getNamedItem("subReportTypes").getNodeValue();
                    creditInvestigationInfo.setSubReportTypes(subReportTypes);
                    String treatResult = cisReport.getAttributes().getNamedItem("treatResult").getNodeValue();
                    creditInvestigationInfo.setTreatResult(treatResult);
                    String refID = cisReport.getAttributes().getNamedItem("refID").getNodeValue();
                    creditInvestigationInfo.setRefID(refID);
                    String hasSystemError = cisReport.getAttributes().getNamedItem("hasSystemError").getNodeValue();
                    creditInvestigationInfo.setHasSystemError(hasSystemError);
                    String isFrozen = cisReport.getAttributes().getNamedItem("isFrozen").getNodeValue();
                    creditInvestigationInfo.setIsFrozen(isFrozen);
                    QueryConditionInfo queryConditionInfo = new QueryConditionInfo();
                    queryConditionInfo.setCaption(cisReport.getElementsByTagName("caption").item(0).getFirstChild().getNodeValue());
                    queryConditionInfo.setName(cisReport.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
                    queryConditionInfo.setValue(cisReport.getElementsByTagName("value").item(0).getFirstChild().getNodeValue());
                    creditInvestigationInfo.setQueryConditionInfo(queryConditionInfo);
                }
            }
            // 个人身份认证信息,在SingleQuery模式下，只可能出现一份.
            NodeList policeCheckInfos = doc.getElementsByTagName("policeCheckInfo");
            if (null != policeCheckInfos && policeCheckInfos.getLength() > 0) {
                for (int pol = 0; pol < policeCheckInfos.getLength(); pol++) {
                    PersonCheckInfo personCheckInfo = new PersonCheckInfo();
                    Element node = (Element) policeCheckInfos.item(pol);
                    NamedNodeMap subReport = node.getAttributes();
                    personCheckInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                    personCheckInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());

                    if (subReport.getNamedItem("treatErrorCode") != null) {
                        personCheckInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                    }

                    personCheckInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                    personCheckInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());

                    // may 0
                    if (node.getElementsByTagName("name").item(0) != null) {
                        personCheckInfo.setName(node.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
                        personCheckInfo.setDocumentNo(node.getElementsByTagName("documentNo").item(0).getFirstChild().getNodeValue());
                        personCheckInfo.setResult(node.getElementsByTagName("result").item(0).getFirstChild().getNodeValue());
                        if (node.getElementsByTagName("photo").item(0).getFirstChild() != null) {
                            personCheckInfo.setPhoto(node.getElementsByTagName("photo").item(0).getFirstChild().getNodeValue());
                        }
                    }
                    personCheckInfo.setCreatetime(currentDate);
                    creditInvestigationInfo.setPersonCheckInfo(personCheckInfo);
                }
            }
            // 个人基本信息
            NodeList personBaseInfos = doc.getElementsByTagName("personBaseInfo");
            if (null != personBaseInfos && personBaseInfos.getLength() > 0) {
                for (int per = 0; per < personBaseInfos.getLength(); per++) {
                    Element node = (Element) personBaseInfos.item(per);
                    PersonBaseInfo personBaseInfo = new PersonBaseInfo();
                    NamedNodeMap subReport = node.getAttributes();
                    personBaseInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                    personBaseInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                    if (subReport.getNamedItem("treatErrorCode") != null) {
                        personBaseInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                    }
                    personBaseInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                    personBaseInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                    personBaseInfo.setName(node.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
                    personBaseInfo.setAge(node.getElementsByTagName("age").item(0).getFirstChild().getNodeValue());
                    personBaseInfo.setDocNo(node.getElementsByTagName("docNo").item(0).getFirstChild().getNodeValue());
                    personBaseInfo.setBirthday(node.getElementsByTagName("birthday").item(0).getFirstChild().getNodeValue());
                    personBaseInfo.setGenderID(node.getElementsByTagName("genderID").item(0).getFirstChild().getNodeValue());
                    personBaseInfo.setOriginalAddress(node.getElementsByTagName("originalAddress").item(0).getFirstChild().getNodeValue());
                    personBaseInfo.setVerifyResult(node.getElementsByTagName("verifyResult").item(0).getFirstChild().getNodeValue());
                    personBaseInfo.setCreatetime(currentDate);
                    
                    creditInvestigationInfo.setPersonBaseInfo(personBaseInfo);
                    
                }
            }
            // 个人法院执行信息,0->n
            NodeList courtInfos = doc.getElementsByTagName("courtInfos");
            List<PersonCourtInfo> personCourtInfos = new ArrayList<PersonCourtInfo>();
            if (null != courtInfos && courtInfos.getLength() > 0) {
                for (int cou = 0; cou < courtInfos.getLength(); cou++) {
                    Element node = (Element) courtInfos.item(cou);
                    NamedNodeMap subReport = node.getAttributes();
                    if (node.getElementsByTagName("name").getLength() > 0) {
                        for (int i = 0; i < node.getElementsByTagName("name").getLength(); i++) {
                            PersonCourtInfo personCourtInfo = new PersonCourtInfo();
                            personCourtInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                            personCourtInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                            if (subReport.getNamedItem("treatErrorCode") != null) {
                                personCourtInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                            }
                            personCourtInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                            personCourtInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());

                            personCourtInfo.setName(node.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setCurrency(node.getElementsByTagName("currency").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setDocumentNo(node.getElementsByTagName("documentNo").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setBelongings(node.getElementsByTagName("belongings").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setExecCourt(node.getElementsByTagName("execCourt").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setStatus(node.getElementsByTagName("status").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setRecordTime(node.getElementsByTagName("recordTime").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setRecordNo(node.getElementsByTagName("recordNo").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setInfoDate(node.getElementsByTagName("infoDate").item(i).getFirstChild().getNodeValue());
                            personCourtInfo.setCreatetime(currentDate);
                            personCourtInfos.add(personCourtInfo);
                        }
                    } else {
                        PersonCourtInfo personCourtInfo = new PersonCourtInfo();
                        personCourtInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                        personCourtInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                        if (subReport.getNamedItem("treatErrorCode") != null) {
                            personCourtInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                        }
                        personCourtInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                        personCourtInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                        personCourtInfo.setCreatetime(currentDate);
                        personCourtInfos.add(personCourtInfo);
                    }
                    creditInvestigationInfo.setPersonCourtInfo(personCourtInfos);
                }
            }
            // 个人担任法定代表人信息 0->n
            NodeList artificialNationalInfos = doc.getElementsByTagName("artificialNationalInfo");
            List<ArtificialNationalInfo> nationalInfos = new ArrayList<ArtificialNationalInfo>();
            if (null != artificialNationalInfos && artificialNationalInfos.getLength() > 0) {
                for (int art = 0; art < artificialNationalInfos.getLength(); art++) {
                    Element node = (Element) artificialNationalInfos.item(art);
                    
                    NamedNodeMap subReport = node.getAttributes();
                    if (node.getElementsByTagName("artificialName").getLength() > 0) {
                        for(int i = 0; i < node.getElementsByTagName("artificialName").getLength(); i++){
                            ArtificialNationalInfo artificialNationalInfo = new ArtificialNationalInfo();
                            artificialNationalInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                            artificialNationalInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                            if (subReport.getNamedItem("treatErrorCode") != null) {
                                artificialNationalInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                            }
                            artificialNationalInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                            artificialNationalInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                            artificialNationalInfo.setArtificialName(node.getElementsByTagName("artificialName").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setCorpName(node.getElementsByTagName("corpName").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setRegisterNo(node.getElementsByTagName("registerNo").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setOrgCode(node.getElementsByTagName("orgCode").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setCorpTypeID(node.getElementsByTagName("corpTypeID").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setCorpTypeCaption(node.getElementsByTagName("corpTypeCaption").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setRegistFund(node.getElementsByTagName("registFund").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setStatusID(node.getElementsByTagName("statusID").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setStatusCaption(node.getElementsByTagName("statusCaption").item(i).getFirstChild().getNodeValue());
                            artificialNationalInfo.setCreatetime(currentDate);
                            nationalInfos.add(artificialNationalInfo);
                        }
                    }else{
                        ArtificialNationalInfo artificialNationalInfo = new ArtificialNationalInfo();
                        artificialNationalInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                        artificialNationalInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                        if (subReport.getNamedItem("treatErrorCode") != null) {
                            artificialNationalInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                        }
                        artificialNationalInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                        artificialNationalInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                        artificialNationalInfo.setCreatetime(currentDate);
                        nationalInfos.add(artificialNationalInfo);
                    }
                    creditInvestigationInfo.setArtificialNationalInfos(nationalInfos);
                }
            }

            // 个人股权投资信息0->n
            NodeList nationalPersonShareholderReports = doc.getElementsByTagName("nationalPersonShareholderReport");
            List<NationalPersonShareholderReport> shareHolders = new ArrayList<NationalPersonShareholderReport>();
            if (null != nationalPersonShareholderReports && nationalPersonShareholderReports.getLength() > 0) {
                for (int national = 0; national < nationalPersonShareholderReports.getLength(); national++) {
                    Element node = (Element) nationalPersonShareholderReports.item(national);
                    NamedNodeMap subReport = node.getAttributes();
                    
                    if(node.getElementsByTagName("name").getLength() > 0){
                        for(int i =0; i < node.getElementsByTagName("name").getLength(); i++){
                            NationalPersonShareholderReport nationalPersonShareholderReport = new NationalPersonShareholderReport();
                            nationalPersonShareholderReport.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                            nationalPersonShareholderReport.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                            if (subReport.getNamedItem("treatErrorCode") != null) {
                                nationalPersonShareholderReport.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                            }
                            nationalPersonShareholderReport.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                            nationalPersonShareholderReport.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                            nationalPersonShareholderReport.setName(node.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setCorpName(node.getElementsByTagName("corpName").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setContributiveFund(node.getElementsByTagName("contributiveFund").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setContributivePercent(node.getElementsByTagName("contributivePercent").item(i).getFirstChild()
                                    .getNodeValue());
                            nationalPersonShareholderReport.setCorpTypeID(node.getElementsByTagName("corpTypeID").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setCorpTypeCaption(node.getElementsByTagName("corpTypeCaption").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setRegistFund(node.getElementsByTagName("registFund").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setStatusID(node.getElementsByTagName("statusID").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setRegistNo(node.getElementsByTagName("registNo").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setStatusCaption(node.getElementsByTagName("statusCaption").item(i).getFirstChild().getNodeValue());
                            nationalPersonShareholderReport.setCreatetime(currentDate);
                            shareHolders.add(nationalPersonShareholderReport);
                        }
                    }else{
                        NationalPersonShareholderReport nationalPersonShareholderReport = new NationalPersonShareholderReport();
                        nationalPersonShareholderReport.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                        nationalPersonShareholderReport.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                        if (subReport.getNamedItem("treatErrorCode") != null) {
                            nationalPersonShareholderReport.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                        }
                        nationalPersonShareholderReport.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                        nationalPersonShareholderReport.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                        nationalPersonShareholderReport.setCreatetime(currentDate);
                        shareHolders.add(nationalPersonShareholderReport);
                    }
                    creditInvestigationInfo.setNationalPersonShareholderReport(shareHolders);
                }
            }

            // 个人担任高管信息0->n
            NodeList personTopManagerInfos = doc.getElementsByTagName("personTopManagerInfo");
            List<PersonTopManagerInfo> topInfos =new ArrayList<PersonTopManagerInfo>();
            if (null != personTopManagerInfos && personTopManagerInfos.getLength() > 0) {
                for (int person = 0; person < personTopManagerInfos.getLength(); person++) {
                    Element node = (Element) personTopManagerInfos.item(person);
                    NamedNodeMap subReport = node.getAttributes();
                    if(node.getElementsByTagName("name").getLength() > 0){
                        for(int i = 0; i < node.getElementsByTagName("name").getLength(); i++){
                            PersonTopManagerInfo personTopManagerInfo = new PersonTopManagerInfo();
                            personTopManagerInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                            personTopManagerInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                            if (subReport.getNamedItem("treatErrorCode") != null) {
                                personTopManagerInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                            }
                            personTopManagerInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                            personTopManagerInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                            personTopManagerInfo.setName(node.getElementsByTagName("name").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setCorpName(node.getElementsByTagName("corpName").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setPositionID(node.getElementsByTagName("positionID").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setPositionCaption(node.getElementsByTagName("positionCaption").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setCorpTypeID(node.getElementsByTagName("corpTypeID").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setCorpTypeCaption(node.getElementsByTagName("corpTypeCaption").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setRegistFund(node.getElementsByTagName("registFund").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setStatusID(node.getElementsByTagName("statusID").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setRegistNo(node.getElementsByTagName("registNo").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setStatusCaption(node.getElementsByTagName("statusCaption").item(i).getFirstChild().getNodeValue());
                            personTopManagerInfo.setCreatetime(currentDate);
                            topInfos.add(personTopManagerInfo);
                        }
                    }else{
                        PersonTopManagerInfo personTopManagerInfo = new PersonTopManagerInfo();
                        personTopManagerInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                        personTopManagerInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                        if (subReport.getNamedItem("treatErrorCode") != null) {
                            personTopManagerInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                        }
                        personTopManagerInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                        personTopManagerInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                        personTopManagerInfo.setCreatetime(currentDate);
                        topInfos.add(personTopManagerInfo);
                    }
                   creditInvestigationInfo.setPersonTopManagerInfo(topInfos);
                }
            }
        } catch (ParserConfigurationException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        } catch (SAXException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        }
        return creditInvestigationInfo;
    }

    @Override
    public String createCompanyXml(CompanyCheckReqInfo req) {
        String xmlStr = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();
            document.setXmlVersion("1.0");
            Element root = document.createElement("conditions");
            document.appendChild(root);

            Element condition = document.createElement("condition");
            condition.setAttribute("queryType", String.valueOf(req.getQueryType()));
            // 企业名称
            Element item = document.createElement("item");
            Element name = document.createElement("name");
            name.setTextContent("corpName");
            item.appendChild(name);
            Element value = document.createElement("value");
            value.setTextContent(req.getCorpName());
            item.appendChild(value);
            condition.appendChild(item);

            // 组织机构代码【可选】
            if (null != req.getOrgCode()) {
                Element item2 = document.createElement("item");
                Element name2 = document.createElement("name");
                name2.setTextContent("orgCode");
                item2.appendChild(name2);
                Element value2 = document.createElement("value");
                value2.setTextContent(req.getOrgCode());
                item2.appendChild(value2);
                condition.appendChild(item2);
            }
            // 工商注册号
            if (null != req.getRegisterNo()) {
                Element item3 = document.createElement("item");
                Element name3 = document.createElement("name");
                name3.setTextContent("registerNo");
                item3.appendChild(name3);
                Element value3 = document.createElement("value");
                value3.setTextContent(req.getRegisterNo());
                item3.appendChild(value3);
                condition.appendChild(item3);
            }
            // 查询电话反查信息
            if (null != req.getTel()) {
                Element item4 = document.createElement("item");
                Element name4 = document.createElement("name");
                name4.setTextContent("tel");
                item4.appendChild(name4);
                Element value4 = document.createElement("value");
                value4.setTextContent(req.getTel());
                item4.appendChild(value4);
                // 机主名称
                if (null != req.getOwnerName()) {
                    Element item5 = document.createElement("item");
                    Element name5 = document.createElement("name");
                    name5.setTextContent("tel");
                    item5.appendChild(name5);
                    Element value5 = document.createElement("value");
                    value5.setTextContent(req.getTel());
                    item5.appendChild(value5);
                    condition.appendChild(item5);
                }
                condition.appendChild(item4);
            }
            
            Element item6 = document.createElement("item");
            Element name6 = document.createElement("name");
            name6.setTextContent("subreportIDs");
            item6.appendChild(name6);
            Element value6 = document.createElement("value");
            value6.setTextContent(req.getSubreportIDs());
            item6.appendChild(value6);
            condition.appendChild(item6);
            
            Element item7 = document.createElement("item");
            Element name7 = document.createElement("name");
            name7.setTextContent("refID");
            item7.appendChild(name7);
            Element value7 = document.createElement("value");
            value7.setTextContent(req.getRefID());
            item7.appendChild(value7);
            condition.appendChild(item7);
            
            
            root.appendChild(condition);
            TransformerFactory transFactory = TransformerFactory.newInstance();
            Transformer transFormer = transFactory.newTransformer();
            transFormer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            DOMSource domSource = new DOMSource(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            transFormer.transform(domSource, new StreamResult(bos));
            xmlStr = bos.toString();
        } catch (ParserConfigurationException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        } catch (TransformerConfigurationException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        } catch (TransformerException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        }
        return replaceCharset(xmlStr);
    }

    private String replaceCharset(String xmlStr) {
        xmlStr = xmlStr.replaceAll("encoding=\"utf-8\"", "encoding=\"GBK\"");
        return xmlStr;
    }

    @Override
    public CreditInvestigationInfo parserCompanyXml(String rsp) {
        CreditInvestigationInfo creditInvestigationInfo = new CreditInvestigationInfo();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader sr = new StringReader(rsp);
            InputSource is = new InputSource(sr);
            Document doc = builder.parse(is);
            // 根节点
            Element rootElement = doc.getDocumentElement();
            NamedNodeMap cisReports = rootElement.getAttributes();
            String batNo = cisReports.getNamedItem("batNo").getNodeValue();
            creditInvestigationInfo.setBatNo(batNo);
            String unitName = cisReports.getNamedItem("unitName").getNodeValue();
            creditInvestigationInfo.setUnitName(unitName);
            String subOrgan = cisReports.getNamedItem("subOrgan").getNodeValue();
            creditInvestigationInfo.setSubOrgan(subOrgan);
            String queryUserID = cisReports.getNamedItem("queryUserID").getNodeValue();
            creditInvestigationInfo.setQueryUserID(queryUserID);
            String queryCount = cisReports.getNamedItem("queryCount").getNodeValue();
            creditInvestigationInfo.setQueryCount(queryCount);
            String receiveTime = cisReports.getNamedItem("receiveTime").getNodeValue();
            creditInvestigationInfo.setReceiveTime(receiveTime);
            NodeList nList = doc.getElementsByTagName("cisReport");
            
            Date currentDate = new Date();
            // 认证头部信息
            if (null != nList && nList.getLength() > 0) {
                // 遍历该集合，显示结合中的元素及其子元素的名字
                for (int cis = 0; cis < nList.getLength(); cis++) {
                    Element cisReport = (Element) nList.item(cis);
                    String reportID = cisReport.getAttributes().getNamedItem("reportID").getNodeValue();
                    creditInvestigationInfo.setReportID(reportID);
                    String buildEndTime = cisReport.getAttributes().getNamedItem("buildEndTime").getNodeValue();
                    creditInvestigationInfo.setBuildEndTime(buildEndTime);
                    String queryReasonID = cisReport.getAttributes().getNamedItem("queryReasonID").getNodeValue();
                    creditInvestigationInfo.setQueryReasonID(queryReasonID);
                    String subReportTypes = cisReport.getAttributes().getNamedItem("subReportTypes").getNodeValue();
                    creditInvestigationInfo.setSubReportTypes(subReportTypes);
                    String treatResult = cisReport.getAttributes().getNamedItem("treatResult").getNodeValue();
                    creditInvestigationInfo.setTreatResult(treatResult);
                    String refID = cisReport.getAttributes().getNamedItem("refID").getNodeValue();
                    creditInvestigationInfo.setRefID(refID);
                    String hasSystemError = cisReport.getAttributes().getNamedItem("hasSystemError").getNodeValue();
                    creditInvestigationInfo.setHasSystemError(hasSystemError);
                    String isFrozen = cisReport.getAttributes().getNamedItem("isFrozen").getNodeValue();
                    creditInvestigationInfo.setIsFrozen(isFrozen);
                    QueryConditionInfo queryConditionInfo = new QueryConditionInfo();
                    queryConditionInfo.setCaption(cisReport.getElementsByTagName("caption").item(0).getFirstChild().getNodeValue());
                    queryConditionInfo.setName(cisReport.getElementsByTagName("name").item(0).getFirstChild().getNodeValue());
                    queryConditionInfo.setValue(cisReport.getElementsByTagName("value").item(0).getFirstChild().getNodeValue());
                    creditInvestigationInfo.setQueryConditionInfo(queryConditionInfo);
                }
            }
            // 企业基本信息
            NodeList corpBaseNationalInfos = doc.getElementsByTagName("corpBaseNationalInfo");
            if (null != corpBaseNationalInfos && corpBaseNationalInfos.getLength() > 0) {
                for (int corp = 0; corp < corpBaseNationalInfos.getLength(); corp++) {
                    Element node = (Element) corpBaseNationalInfos.item(corp);
                    CorpBaseNationalInfo corpBaseNationalInfo = new CorpBaseNationalInfo();
                    NamedNodeMap subReport = node.getAttributes();
                    corpBaseNationalInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                    corpBaseNationalInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                    if (subReport.getNamedItem("treatErrorCode") != null) {
                        corpBaseNationalInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                    }
                    corpBaseNationalInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                    corpBaseNationalInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());

                    if(node.getElementsByTagName("corpName").getLength() > 0){
                        corpBaseNationalInfo.setCorpName(node.getElementsByTagName("corpName").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setCorpTypeID(node.getElementsByTagName("corpTypeID").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setCorpTypeCaption(node.getElementsByTagName("corpTypeCaption").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setRegistFund(node.getElementsByTagName("registFund").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setStatusID(node.getElementsByTagName("statusID").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setOrgCode(node.getElementsByTagName("orgCode").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setRegisterNo(node.getElementsByTagName("registerNo").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setArtificialName(node.getElementsByTagName("artificialName").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setArtificialName2(node.getElementsByTagName("artificialName2").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setRegistDate(node.getElementsByTagName("registDate").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setHandleDate(node.getElementsByTagName("handleDate").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setCancelDate(node.getElementsByTagName("cancelDate").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setUrl(node.getElementsByTagName("url").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setFlag(node.getElementsByTagName("flag").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setStatusID2(node.getElementsByTagName("statusID2").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setStatusCaption2(node.getElementsByTagName("statusCaption2").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setFundCurrency(node.getElementsByTagName("fundCurrency").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setRegistFund2(node.getElementsByTagName("registFund2").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setFundCurrency2(node.getElementsByTagName("fundCurrency2").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setOrganType(node.getElementsByTagName("organType").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setEconomicType(node.getElementsByTagName("economicType").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setStaffNumber(node.getElementsByTagName("staffNumber").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setTradeCode(node.getElementsByTagName("tradeCode").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setTradeName1(node.getElementsByTagName("tradeName1").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setTradeName2(node.getElementsByTagName("tradeName2").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setTradeName3(node.getElementsByTagName("tradeName3").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setTradeName4(node.getElementsByTagName("tradeName4").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setManageRange(node.getElementsByTagName("manageRange").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setOpenDate(node.getElementsByTagName("openDate").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setManageBeginDate(node.getElementsByTagName("manageBeginDate").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setManageEndDate(node.getElementsByTagName("manageEndDate").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setAllowManageProject(node.getElementsByTagName("allowManageProject").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setGeneralManageProject(node.getElementsByTagName("generalManageProject").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setManageRangeFashion(node.getElementsByTagName("manageRangeFashion").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setRegisterDepartment(node.getElementsByTagName("registerDepartment").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setLastCheckYear(node.getElementsByTagName("lastCheckYear").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setLastCheckDate(node.getElementsByTagName("lastCheckDate").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setLogoutDate(node.getElementsByTagName("logoutDate").item(0).getFirstChild().getNodeValue());
                        corpBaseNationalInfo.setRevokeDate(node.getElementsByTagName("revokeDate").item(0).getFirstChild().getNodeValue());
                    }
                    corpBaseNationalInfo.setCreatetime(currentDate);
                    creditInvestigationInfo.setCorpBaseNationalInfo(corpBaseNationalInfo);
                }
            }
            // 企业法院执行信息
            NodeList courtInfos = doc.getElementsByTagName("courtInfos");
            List<CompanyCourtInfo> companyCourtInfos = new ArrayList<CompanyCourtInfo>();
            if (null != courtInfos && courtInfos.getLength() > 0) {
                for (int cou = 0; cou < courtInfos.getLength(); cou++) {
                    Element node = (Element) courtInfos.item(cou);
                    NamedNodeMap subReport = node.getAttributes();
                    
                    if(node.getElementsByTagName("corpName").getLength() > 1){
                        for(int i = 0; i < node.getElementsByTagName("corpName").getLength(); i++){
                            CompanyCourtInfo companyCourtInfo = new CompanyCourtInfo();
                            companyCourtInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                            companyCourtInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                            if (subReport.getNamedItem("treatErrorCode") != null) {
                                companyCourtInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                            }
                            companyCourtInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                            companyCourtInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                            companyCourtInfo.setCorpName(node.getElementsByTagName("corpName").item(0).getFirstChild().getNodeValue());
                            companyCourtInfo.setCurrency(node.getElementsByTagName("currency").item(0).getFirstChild().getNodeValue());
                            companyCourtInfo.setBelongings(node.getElementsByTagName("belongings").item(0).getFirstChild().getNodeValue());
                            companyCourtInfo.setExecCourt(node.getElementsByTagName("execCourt").item(0).getFirstChild().getNodeValue());
                            companyCourtInfo.setStatus(node.getElementsByTagName("status").item(0).getFirstChild().getNodeValue());
                            companyCourtInfo.setRecordTime(node.getElementsByTagName("recordTime").item(0).getFirstChild().getNodeValue());
                            companyCourtInfo.setRecordNo(node.getElementsByTagName("recordNo").item(0).getFirstChild().getNodeValue());
                            companyCourtInfo.setInfoDate(node.getElementsByTagName("infoDate").item(0).getFirstChild().getNodeValue());
                            companyCourtInfo.setCreatetime(currentDate);
                            companyCourtInfos.add(companyCourtInfo);
                        }
                    }else{
                        CompanyCourtInfo companyCourtInfo = new CompanyCourtInfo();
                        companyCourtInfo.setSubReportType(subReport.getNamedItem("subReportType").getNodeValue());
                        companyCourtInfo.setSubReportTypeCost(subReport.getNamedItem("subReportTypeCost").getNodeValue());
                        if (subReport.getNamedItem("treatErrorCode") != null) {
                            companyCourtInfo.setTreatErrorCode(subReport.getNamedItem("treatErrorCode").getNodeValue());
                        }
                        companyCourtInfo.setErrorMessage(subReport.getNamedItem("errorMessage").getNodeValue());
                        companyCourtInfo.setTreatResult(subReport.getNamedItem("treatResult").getNodeValue());
                        companyCourtInfo.setCreatetime(currentDate);
                        companyCourtInfos.add(companyCourtInfo);
                    }
                    creditInvestigationInfo.setCompanyCourtInfo(companyCourtInfos);
                }
            }
        } catch (ParserConfigurationException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        } catch (SAXException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            logger.warn(e.toString());
            e.printStackTrace();
        }
        return creditInvestigationInfo;
    }

    public static void main(String[] args) throws Exception {
        PyXmlServiceImpl impl = new PyXmlServiceImpl();

        //String txt = FileUtil.readTotalFile("d:\\personal2.xml");
        // CompanyCheckReqInfo checkReqInfo = new CompanyCheckReqInfo();
        // checkReqInfo.setCorpName("上海牛娃对方答复答复我是一个兵");
        // checkReqInfo.setOrgCode("43589302483924932");
        // checkReqInfo.setQueryType(3454354);
        // checkReqInfo.setRegisterNo("b134324s3343");
        // System.out.println(impl.createCompanyXml(checkReqInfo));

        //System.out.println(impl.parserPersonXml(txt, "36252198608220031"));
        
        String com = FileUtil.readTotalFile("d:\\company.xml");
        System.out.println(impl.parserCompanyXml(com));
    }

}
